//
//  OAacountSetViewController.m
//  LongOA
//
//  Created by 耿用强 on 15/7/5.
//  Copyright (c) 2015年 耿用强. All rights reserved.
//

#import "OAacountSetViewController.h"
#import "OAacountSetCell.h"
#import "AppDelegate.h"
#import "OAIndexViewController.h"
#import "OALoginView.h"
#import "ILJClient.h"
#import "P1Client.h"
#import "ILJClientCreator.h"
#import "P1ClientCreator.h"
#import "LJClientPool.h"
#import "OAAccount.h"
#import "OALoginViewController.h"
#import "OASet.h"

#import "LoginRequest.h"
#import "LoginResponse.h"

@interface OAacountSetViewController ()<UITableViewDataSource,UITableViewDelegate,OALoginViewDelegate>
{
    NSMutableDictionary* _sets;
    NSMutableArray* _setids;
    NSArray*_dataArray;
    OALoginView*_loingView;
    
    OAAccount*_dataDic;
}
@end

@implementation OAacountSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavBarleftBtn:@"" andlDimg:@"" rightBtn:@"Common/btn_add" andrImg:@"" title:@"帐套设置" ];
    [self buildTables:CGRectMake(0, HEADER_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-HEADER_HEIGHT) andHeaderView:nil andFooterView:nil andAlwaysBounceVertical:YES Delegate:self DataSouce:self];
    [[OAIpdataBase shareInstance] initAccounts];
    _dataArray=[[OAIpdataBase shareInstance] allAccounts];
    _sets = [[NSMutableDictionary alloc] init];
    _setids = [[NSMutableArray alloc] init];
    
    for (OAAccount* account in _dataArray) {
        NSMutableArray* sub = [_sets objectForKey:[NSNumber numberWithInt:account.setid]];
        if (!sub) {
            sub = [[NSMutableArray alloc] init];
            [_sets setObject:sub forKey:[NSNumber numberWithInt:account.setid]];
            [_setids addObject:[NSNumber numberWithInt:account.setid]];
        }
        
        [sub addObject:account];
    }
    
    _loingView=[[OALoginView alloc]initWithFrame:CGRectMake(0, HEADER_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-HEADER_HEIGHT)];
    _loingView.delegate=self;
    _loingView.alpha=0;

    [self.view addSubview:_loingView];

    // Do any additional setup after loading the view.
}

- (UIView*)headerView
{
    UIView*header=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, RESIZE_UI(30))];
    header.backgroundColor=[UIColor lightGrayColor];
    UILabel*textLabel=[[UILabel alloc]initWithFrame:CGRectMake(RESIZE_UI(10), 0, header.width-RESIZE_UI(20), header.height)];
    textLabel.textColor=[UIColor darkGrayColor];
    textLabel.text=@"LJService";
    [header addSubview:textLabel];
    
    return header;
}


#pragma mark- UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_sets count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSNumber* setid = [_setids objectAtIndex:section];
    return [[_sets objectForKey:setid] count];
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // DONE:按服务器分栏显示
    static NSString*OAacountCellIdentifer=@"OAacountCellIdentifer";
    OAacountSetCell*cell=[tableView dequeueReusableCellWithIdentifier:OAacountCellIdentifer];
    if (cell==nil) {
        cell=[[OAacountSetCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:OAacountCellIdentifer];
    }
    
    NSNumber* key = [_setids objectAtIndex:indexPath.section];
    NSArray* subs = [_sets objectForKey:key];
    
    [cell showCellData:subs[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return RESIZE_UI(50);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber* key = [_setids objectAtIndex:indexPath.section];
    NSArray* subs = [_sets objectForKey:key];
    
    _dataDic=subs[indexPath.row];
    //NSLog(@"%@=",_dataDic);
    [_loingView show];
}

- (NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSNumber* key = [_setids objectAtIndex:section];
    OASet* set = [[OAIpdataBase shareInstance] getSet:[key intValue]];
    return set.name;
}

#pragma mark - LoginViewDelegate
- (void)doLoginMethod:(NSString *)userName andPassword:(NSString *)password
{
    
//    private String account;
//    private String userid;
//    private String password;
//    private String token;
    LoginRequest* request = [[LoginRequest alloc] init];
    request.account = _dataDic.name;
    request.userid = userName;
    request.password = password;
    
//    NSMutableDictionary*_need=[[NSMutableDictionary alloc]init];
//
//    [_need setObject:_dataDic.name forKey:@"account"];
//    [_need setObject:userName forKey:@"userid"];
//    [_need setObject:password forKey:@"password"];
//    [_need setObject:@"" forKey:@"token"];
    
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:_dataDic.setid];
    [clinet Doexecute:request
RspClass:[LoginResponse class]
andMsg:@"正在登录..."
andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    LoginResponse* rslt = rsp;
    if (rslt.ErrMsg) {
        NSLog(rslt.ErrMsg);
    }
    else{
        //NSLog(@"%@",rslt.token);
        _dataDic.token = rslt.token;
        _dataDic.userid = request.userid;
        _dataDic.username = rslt.username;
        _dataDic.hasLogin = YES;
        [_dataDic saveToDB];
        [_loingView hide];
        [[self tableView] reloadData];
        //NSLog(@"==%@",_dataDic);
    }
}];
    
//    [clinet requestWithApiName:@"Login" params:_need andMsg:@"正在登录..." andView:self.view globalTimelinePostsWithBlock:^(NSDictionary*result,NSError*error){
//        if (!error) {
//            NSString* ErrMsg = [result objectForKey:@"ErrMsg"];
//            if (ErrMsg) {
//                NSLog(ErrMsg);
//            }
//            else{
//                _dataDic.token = [result objectForKey:@"token"];
//                _dataDic.userid = [result objectForKey:@"userid"];
//                _dataDic.username = [result objectForKey:@"username"];
//                _dataDic.hasLogin = YES;
//                [_loingView hide];
//                [[self tableView] reloadData];
//            }
//            
////            NSLog(@"%@",result);
////            [GolbalManager sharedManager].loginInfo=[OALoingInfo oaLoginInfoWithdic:result];
////            
////            OAIndexViewController*indexVc=[[OAIndexViewController alloc]init];
////            AppDelegate*app=APPDELEGATE;
////            app.window.rootViewController=indexVc;
//        }
//        else
//        {
//            
//        }
//    
//        
//    }];
    
//    [OANetPublic requestWithApiName:@"Login" params:_need andTag:1 andMsg:@"正在登录..." andView:self.view globalTimelinePostsWithBlock:^(NSDictionary*result,NSError*error){
//        if (!error) {
//            NSLog(@"%@",result);
//            [GolbalManager sharedManager].loginInfo=[OALoingInfo oaLoginInfoWithdic:result];
//            
//                OAIndexViewController*indexVc=[[OAIndexViewController alloc]init];
//                AppDelegate*app=APPDELEGATE;
//                app.window.rootViewController=indexVc;            
//            
//        }
//        else
//        {
//            
//        }
//    
//    
//    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void) rightBtnAction
{
    OAIpdataBase* dbcache = [OAIpdataBase shareInstance];
    [dbcache initAccounts];
    
    NSArray* accounts = [dbcache allAccounts];
    NSArray* loginAccouts = [dbcache loginAccounts];
    
    AppDelegate*app=APPDELEGATE;
    if (loginAccouts.count > 0)
    {       
        // 打开主界面
        OAIndexViewController*indexVc=[[OAIndexViewController alloc]init];
        [self.view removeFromSuperview];
        //OAEmailViewController* indexVc=[[OAEmailViewController alloc] init];
        app.window.rootViewController=indexVc;
    }
    else if (accounts.count > 0)
    {
        // 提示登录
    }
    else
    {
        // 打开服务器设置界面并打开添加服务器窗口
        OALoginViewController*loginVc=[[OALoginViewController alloc]init];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:loginVc];
        nav.navigationBarHidden=YES;
        app.window.rootViewController = nav;
    }
}

@end
